import json
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt
from django import forms
from app01 import models
from app01.utils.bootstrapForm import BootstrapModelForm
from app01.utils.pagination import Pagination


class TaskModelForm(BootstrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.TextInput
        }


@csrf_exempt
def task_add(request):
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))
    data_dict = {
        'status': False,
        'errors': form.errors,
    }
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))


def task_list(request):
    queryset = models.Task.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    html_text = page_object.html
    page_query_set = page_object.page_query_set

    form = TaskModelForm()
    context = {
        'form': form,
        'queryset': queryset,
        'page_html': html_text,
    }
    return render(request, "task_list.html", context)
